from flask import abort, jsonify
from flask import g
from flask import request
from flask import session

from info.constants import HOME_PAGE_MAX_NEWS
from info.models import News, Category, User
from . import home_blu
from flask import render_template, current_app

# 2.使用蓝图注册路由
from info.utils.common import user_login_data
from info.utils.response_code import RET, error_map


@home_blu.route('/')
@user_login_data
def index():
    # 按照`点击量`查询`前10条`新闻数据
    news_list = []
    try:
        news_list = News.query.order_by(News.clicks.desc()).limit(10).all()
    except BaseException as e:
        current_app.logger.error(e)

    news_list = [news.to_dict() for news in news_list]

    # 查询所有的分类数据, 后端模板渲染
    categories = []
    try:
        categories = Category.query.all()
    except BaseException as e:
        current_app.logger.error(e)

    # 将模型转为字典
    user = g.user.to_dict() if g.user else None

    # 将用户信息传入模板渲染
    return render_template("new/index.html", user=user, news_list=news_list, categories=categories)


@home_blu.route('/favicon.ico')
def favicon():
    # 网站小图标的请求是由浏览器自动发起的, 只需要实现该路由并返回图标对应图片即可
    # flask中内置了获取静态文件的语法send_static_file, flask访问静态文件的路由底层也是调用该方法
    return current_app.send_static_file("news/favicon.ico")


# 获取新闻列表
@home_blu.route('/get_news_list')
def get_news_list():
    # 获取参数  分类id 当前页码  总页码 每页条数
    cid = request.args.get('cid')
    cur_page = request.args.get('cur_page')
    per_count = request.args.get('per_count', HOME_PAGE_MAX_NEWS)
    # 校正参数  分类 当前页码必须
    if not all([cid, cur_page]):
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

    # 格式转换
    try:
        cid = int(cid)
        cur_page = int(cur_page)
        per_count = int(per_count)
    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

    # 按照分类id查出条数新闻 并按照倒序排列   及排除未
    try:
        if cid != 1:
            pn = News.query.filter(News.status == 0, News.category_id == cid).order_by( News.create_time.desc()).paginate(cur_page,
                                                                                                       per_count)
        else:
            pn = News.query.filter(News.status == 0).order_by( News.create_time.desc()).paginate(cur_page, per_count)

    except BaseException as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg=error_map[RET.DBERR])

    # 新闻必须审核通过才能显示
    # filter_list = [News.status == 0]
    # # 判断分类是否为"最新"
    # if cid != 1:
    #     filter_list.append(News.category_id == cid)
    #
    # # 按照分类和页码获取新闻数据   发布时间倒序
    # try:
    #     pn = News.query.filter(*filter_list).order_by(News.create_time.desc()).paginate(cur_page, per_count)
    #
    # except BaseException as e:
    #     current_app.logger.error(e)
    #     return jsonify(errno=RET.DBERR, errmsg=error_map[RET.DBERR])

    # 包装到json中返回
    data = {
        "news_list": [news.to_dict() for news in pn.items],
        "total_page": pn.pages
    }
    # 返回接送
    return jsonify(errno=RET.OK, errmsg=error_map[RET.OK], data=data)
